package com.yxhl.zoume.data.tcp;

import com.yxhl.protobuf.TcpRequest;
import com.yxhl.protobuf.TcpResponse;
import com.yxhl.zoume.data.DataConstants;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.inject.Inject;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * Created by Xboy on 16/6/10.
 */

public class TcpClient {

    private static final String KEY_TAG = "TcpClient";
    // 连接状态
    public static boolean isConnect = false;
    // 是否主动断开
    public static boolean isHandClose = false;
    private static Channel channel;


    @Inject
    public TcpClient() {
    }

    /**
     * 配置引导
     *
     * @param
     * @return
     */
    private static Bootstrap configureBootstrap(final OnChannelListener onChannelListener) {
        final TcpClientHandler clientHandler = new TcpClientHandler(onChannelListener);
        Bootstrap b = new Bootstrap();
        b.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .remoteAddress(DataConstants.TcpConstants.HOST, DataConstants.TcpConstants.PORT)
                .handler(clientHandler)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast("gzipDecoder", ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP))
                                .addLast("gzipEncoder", ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP))
                                .addLast("protobufFrameDecoder", new ProtobufVarint32FrameDecoder())
                                .addLast(new ProtobufDecoder(TcpResponse.getDefaultInstance()))
                                .addLast(new ProtobufVarint32LengthFieldPrepender())
                                .addLast(new ProtobufEncoder())
                                .addLast(clientHandler);
                    }
                });

        return b;
    }

    /**
     * 配置引导
     *
     * @param
     * @return
     */
    private static Bootstrap configureBootstrap() {
        final TcpClientHandler clientHandler = new TcpClientHandler();
        Bootstrap b = new Bootstrap();
        b.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .remoteAddress(DataConstants.TcpConstants.HOST, DataConstants.TcpConstants.PORT)
                .handler(clientHandler)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast("gzipDecoder", ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP))
                                .addLast("gzipEncoder", ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP))
                                .addLast("protobufFrameDecoder", new ProtobufVarint32FrameDecoder())
                                .addLast(new ProtobufDecoder(TcpResponse.getDefaultInstance()))
                                .addLast(new ProtobufVarint32LengthFieldPrepender())
                                .addLast(new ProtobufEncoder())
                                .addLast(clientHandler);
                    }
                });

        return b;
    }

    public static void startConnect(final OnChannelListener onChannelListener) {
        if (isHandClose) {// 主动断开连接
            return;
        }
        Bootstrap b = configureBootstrap(onChannelListener);
        ChannelFuture cf = b.connect().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    isConnect = true;
                    Logger.getLogger(KEY_TAG).log(Level.INFO, ":::::::: 连接成功 :::::::::");
                    onChannelListener.onConnectionSuccess();
                } else {
                    isConnect = false;

                    // 尝试重连
                    final EventLoop loop = future.channel().eventLoop();
                    loop.schedule(new Runnable() {
                        @Override
                        public void run() {
                            Logger.getLogger(KEY_TAG).log(Level.INFO, ":::::::: 重连中.... :::::::::");
                            startConnect(onChannelListener);
                        }
                    }, DataConstants.TcpConstants.RECONNECT_DELAY, TimeUnit.MILLISECONDS);
                }
            }
        });

        channel = cf.channel();
    }

    /**
     * startConnect without OnChannelListener
     */
    public static void startConnect() {
        if (isHandClose) {// 主动断开连接
            return;
        }
        Bootstrap b = configureBootstrap();
        ChannelFuture cf = b.connect().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    isConnect = true;
                    Logger.getLogger(KEY_TAG).log(Level.INFO, ":::::::: 连接成功 :::::::::");
                } else {
                    isConnect = false;
                    // 尝试重连
                    final EventLoop loop = future.channel().eventLoop();
                    loop.schedule(new Runnable() {
                        @Override
                        public void run() {
                            Logger.getLogger(KEY_TAG).log(Level.INFO, ":::::::: 重连中.... :::::::::");
                            startConnect();
                        }
                    }, DataConstants.TcpConstants.RECONNECT_DELAY, TimeUnit.MILLISECONDS);
                }
            }
        });

        channel = cf.channel();
    }

    /**
     * 建立连接, 失败重连
     */
    public void connect(OnChannelListener onChannelListener) {
        if (!isConnect()) {
            startConnect(onChannelListener);
        }
    }

    /**
     * 建立连接, 失败重连(去掉channel监听，使用RxBus)
     */
    public void connect() {
        if (!isConnect()) {
            startConnect();
        }
    }

    /**
     * 连接状态
     *
     * @return
     */
    public boolean isConnect() {
        return isConnect;
    }

    /**
     * 向服务端发送请求
     *
     * @param request
     */
    public boolean sendRequest(TcpRequest request) {
        if (isConnect()) {
            ChannelFuture channelFuture = channel.writeAndFlush(request);
            Logger.getLogger(KEY_TAG).log(Level.INFO, "============TCPRequest:=========== /n " + request.toString());
            return channelFuture.isSuccess();
        } else {
            Logger.getLogger(TcpClient.class.getName())
                    .log(Level.WARNING, ":::::::::::::发送数据:::::TCP尚未建立连接:::::::::::::");
        }
        return false;
    }

    /**
     * 主动断开连接
     */
    public void close() {
        if (isConnect()) {
            isHandClose = true;
            channel.close();
        }
    }

    private void logPrintf(String msg) {
        Logger.getLogger("TcpClientHandler").log(Level.INFO, msg);
    }

}
